<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>基于jquery实现的ajax演示</title>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery@3.5/dist/jquery.js"></script>
</head>
<body>
  <form method="post">
    <input type="text" name="field" placeholder="10个字符以内" onblur="inquire(this.value)">
    <input type="button" value="注册" disabled="disabled" onclick="register(this.value)">
  </form>
  <script>
    let message = null;
    function setXHR(params) {
      return {
        url : "server",
        method : "POST",
        headers : {
          "content-type" : "application/x-www-form-urlencoded"
        },
        data : params.data,
        success : params.success
      }
    }
    function inquire(val) {
      if (general(val) === -1)
        return;
      const param = $("form:first>input:nth-child(1)").val();
      $.ajax(setXHR({
        data : {
          "read" : param
        },
        success : function (responseText) {
          var button = $("form:first>input:nth-child(2)");
          if (responseText === "0") {
            message.css("color", "green");
            button.prop("disabled", false);
          } else {
            message.css("color", "red");
            button.prop("disabled", true);
          }
          switch (responseText) {
          case "0":
            message.text("此字段可用");
            break;
          case "1":
            message.text("此字段已被注册");
            break;
          case "-1":
            message.html("服务器可能遇到问题或<b>参数以UTF-8编码转化为字节数组的长度大于10</b>");
          }
        }
      }));
    }
    function register(val) {
      if (general(val) === -1)
        return;
      const param = $("form:first>input:nth-child(1)").val();
      $.ajax(setXHR({
        data : {
          "write" : param
        },
        success : function (responseText) {
          message.css("color", responseText === "1" ? "green" : "red");
          $("form:first>input:nth-child(2)").prop("disabled", true);
          switch (responseText) {
          case "0":
            message.text("此字段已被注册");
            break;
          case "1":
            message.text("注册成功");
            break;
          case "-1":
            message.html("服务器可能遇到问题或<b>参数以UTF-8编码转化为字节数组的长度大于10</b>");
          }
        }
      }));
    }
    function general(param) {
      message = $("#message");
      if (message.get(0) == null) {
        $("form:first").append("<span id='message'></span>");
        general(param);
      }
      var button = $("form:first>input:nth-child(2)");
      if (param === null || param === '') {
        message.css("color", "red");
        message.text("字段为空");
        button.prop("disabled", true);
        return -1;
      }
      if (param.length > 10) {
        message.css("color", "red");
        message.text("参数的长度大于10");
        button.prop("disabled", true);
        return -1;
      }
    }
  </script>
</body>
</html>
